<template>
  <div class="grille-container">
    <!-- 目录 -->
    <cascader-catalog v-model:category-id="query.categoryId" :category-type="categoryType" :title="'试题目录'" @refresh="handlePage" />
    <div class="main-container">
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane :key="0" :label="'全部'" :name="0" />
        <el-tab-pane v-for="item in tabPanes" :key="item.code" :label="item.desc" :name="item.code" />
      </el-tabs>
      <el-form :model="query" inline>
        <el-form-item>
          <el-button v-permission="'question:save'" type="primary" @click="toQuestionUpdate({})">添加试题</el-button>
          <el-button v-permission="'question:ai'" type="success" @click="toAiQuestion">AI出题</el-button>
          <el-button v-permission="'question:edit'" style="margin-left: 10px" :disabled="!ids.length > 0" @click="handleBatchMove()">批量移动</el-button>
          <el-button v-permission="'question:delete'" style="margin-left: 10px" :disabled="!ids.length > 0" @click="handleBatchDelete()">批量删除</el-button>
        </el-form-item>
        <el-form-item>
          <el-input v-model="query.questionTitle" placeholder="请输入试题名称" prefix-icon="Search" clearable />
        </el-form-item>
        <el-form-item>
          <enum-select v-model="query.difficultyLevel" :enum-name="'DifficultyLevel'" :title="'请选择难度等级'" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery()"> 查询</el-button>
          <el-button @click="resetQuery()">重置</el-button>
          <common-sort @sort="handleSort" />
        </el-form-item>
      </el-form>
      <el-table v-loading="page.loading" :data="page.list" row-key="id" class="drag-table" @selection-change="handleSelectionChange">
        <el-table-column type="selection" :width="40" />
        <el-table-column :min-width="100" label="试题名称" prop="questionTitle">
          <template #default="scope">
            <span v-html="scope.row.questionTitle" />
          </template>
        </el-table-column>
        <el-table-column :min-width="20" label="题型" prop="questionType">
          <template #default="scope">
            <enum-view :enum-name="'QuestionType'" :enum-value="scope.row.questionType" />
          </template>
        </el-table-column>
        <el-table-column :min-width="20" label="难度" prop="difficultyLevel">
          <template #default="scope">
            <enum-view :enum-name="'DifficultyLevel'" :enum-value="scope.row.difficultyLevel" />
          </template>
        </el-table-column>
        <el-table-column :min-width="20" label="状态" prop="cite">
          <template #default="scope">
            <span v-if="scope.row.cite">已引用</span>
            <span v-if="!scope.row.cite">未引用</span>
          </template>
        </el-table-column>
        <el-table-column :min-width="25" label="创建时间" prop="gmtCreate"></el-table-column>
        <el-table-column :width="220" fixed="right" label="操作" prop="address">
          <template #default="scope">
            <el-button v-permission="'question:edit'" link type="primary" @click="toQuestionUpdate(scope.row)"> 编辑</el-button>
            <el-divider v-permission="'question:preview'" direction="vertical" />
            <el-button v-permission="'question:preview'" link type="primary" @click="handlePreview(scope.row)"> 预览</el-button>
            <el-divider direction="vertical" />
            <el-dropdown>
              <el-button link type="primary">
                更多操作
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <div v-permission="'question:save'" @click="toQuestionUpdate({ id: scope.row.id, isCopy: true })">
                    <el-dropdown-item>复制</el-dropdown-item>
                  </div>
                  <div v-permission="'question:delete'" @click="handleDeleteByCite(scope.row)">
                    <el-dropdown-item>删除</el-dropdown-item>
                  </div>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <common-pagination v-model:page="page" @pagination="handlePage" />
    </div>
  </div>
  <common-cite v-if="citeRef.visible" :title="citeRef.title" :question-id="citeRef.questionId" :visible="citeRef.visible" @close="citeRef.visible = false" />
  <catalog-move v-if="catalogMoveVisible" :ids="ids" :category-type="categoryType" :visible="catalogMoveVisible" @callback="handleMove" />
  <preview-question v-if="previewQuestionRef.visible" :visible="previewQuestionRef.visible" :question-id="previewQuestionRef.questionId" @close="previewQuestionRef.visible = false" />
</template>

<script setup>
  import useTable from '@/utils/table.js'
  import { onMounted, reactive, ref } from 'vue'
  import CatalogMove from '@/components/Cascader/Catalog/CatalogMove.vue'
  import CommonPagination from '@/components/Common/Pagination/index.vue'
  import PreviewQuestion from '@/components/Preview/Question/index.vue'
  import { questionApi } from '@/api/question.js'
  import { getEnumList } from '@/utils/enum'
  import CascaderCatalog from '@/components/Cascader/Catalog/index.vue'
  import CommonCite from '@/components/Common/Cite.vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import EnumView from '@/components/Enum/View/index.vue'
  import EnumSelect from '@/components/Enum/Select/index.vue'
  import { useRouter } from 'vue-router'
  import CommonSort from '@/components/Common/Sort/index.vue'

  const router = useRouter()
  const categoryType = ref(3) // 1为固定值

  // AI出题
  const toAiQuestion = () => {
    router.push({ path: '/questions/ai' })
  }

  // 预览功能
  const previewQuestionRef = reactive({
    visible: false
  })
  const handlePreview = (row) => {
    previewQuestionRef.visible = true
    previewQuestionRef.questionId = row.id
  }

  // 批量选择
  const ids = ref([])
  const handleSelectionChange = (rows) => {
    ids.value = []
    rows.forEach((row) => {
      ids.value.push(row.id)
    })
  }

  // 批量移动
  const catalogMoveVisible = ref(false)
  const handleBatchMove = () => {
    catalogMoveVisible.value = true
  }
  const handleMove = async (row) => {
    if (row) {
      await questionApi.questionMove(row)
      ElMessage.success('修改成功')
      await handlePage()
    }
    catalogMoveVisible.value = false
  }

  // 删除
  const citeRef = reactive({})
  const handleDeleteByCite = async (row) => {
    if (row.cite) {
      citeRef.visible = true
      citeRef.questionId = row.id
      citeRef.title = row.questionTitle
    } else {
      handleDelete(row)
    }
  }

  // 批量删除
  const handleBatchDelete = async () => {
    ElMessageBox.confirm('若试题被引用无法删除，未被引用的试题删除后将无法恢复，确认删除？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      questionApi.questionBatchDelete(ids.value).then((res) => {
        ElMessage.success(res)
        handlePage()
      })
    })
  }

  // 修改
  const toQuestionUpdate = (item) => {
    router.push({ path: '/questions/update', query: { questionId: item.id, isCopy: item.isCopy } })
  }

  // 类型
  const activeName = ref(0)
  const tabPanes = ref()
  onMounted(async () => {
    tabPanes.value = await getEnumList('QuestionType')
  })
  const handleTabClick = (tab) => {
    activeName.value = tab.props.name
    query.questionType = tab.props.name > 0 ? tab.props.name : undefined
    handleQuery()
  }

  // 基础功能
  const { page, handlePage, query, handleQuery, resetQuery, handleDelete, handleSort } = useTable({
    page: questionApi.questionPage,
    delete: questionApi.questionDelete,
    sort: questionApi.questionSort
  })
</script>
